<template>
    <h-section class="strategyCanvas-wrap">
        <template #title>
            <flexbox>
                <my-icon type="iconzhanlve" style="font-size: 24px; color: #9277fc" />
                <span class="margin-l-8">战略画布</span>
            </flexbox>
        </template>
        <template #titleExtra>
            <flexbox justify="space-between" style="width: 100%">
                <div style="font-size: 12px; color: #70798b">
                    <span class="margin-l-8">这里你可以添加多个竞品，多个竞争要素，并通过图表观察本产品到与竞品同质化程序关系</span>
                </div>
                <!-- 生成画布后的操作按钮 -->
                <flexbox justify="flex-end" align="center" v-if="current === 2">
                    <div class="cursor-pointer" @click="handleEdit">
                        <EditOutlined />
                        <span class="margin-l-8">编辑</span>
                    </div>
                    <div class="cursor-pointer margin-l-8" @click="handleDelete">
                        <DeleteOutlined />
                        <span class="margin-l-8">删除</span>
                    </div>
                </flexbox>
            </flexbox>
        </template>

        <div class="plan-form-wrap">
            <a-steps :current="current" v-if="showStep">
                <a-step v-for="item in steps" :key="item.title" :title="item.title" />
            </a-steps>
            <div class="steps-content">
                <a-empty
                    image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                    :image-style="{
                        height: '60px',
                    }"
                    v-if="current === -1"
                >
                    <template #description>
                        <span> 战略画布离散图 </span>
                    </template>
                    <a-button type="primary" @click="handleAdd" v-if="!disabled">
                        <PlusOutlined />
                        <span>新建</span>
                    </a-button>
                </a-empty>
                <flexbox align="flex-start" v-if="current === 0">
                    <div class="steps-content-item">
                        <flexbox justify="center" class="steps-content-item-header">竞品列表</flexbox>
                        <div class="steps-content-item-body">
                            <flexbox orient="vertical" align="flex-start">
                                <a-row style="width: 100%">
                                    <a-col :span="24" v-for="(item, index) of listForm" :key="index">
                                        <flexbox class="form-item">
                                            <a-input v-model:value="item.name" />
                                            <CloseOutlined style="margin-left: 8px" @click="deleteForm('list', index)" />
                                        </flexbox>
                                    </a-col>
                                </a-row>
                                <a-button type="dashed" @click="addForm('list')">
                                    <PlusOutlined />
                                    <span>添加竞品</span>
                                </a-button>
                            </flexbox>
                        </div>
                    </div>

                    <div class="steps-content-item">
                        <flexbox justify="center" class="steps-content-item-header">竞争要素</flexbox>
                        <div class="steps-content-item-body">
                            <flexbox orient="vertical" align="flex-start">
                                <a-row style="width: 100%">
                                    <a-col :span="24" v-for="(item, index) of elementForm" :key="index">
                                        <flexbox class="form-item">
                                            <a-input v-model:value="item.name" :disabled="item.disabled" />
                                            <CloseOutlined style="margin-left: 8px" @click="deleteForm('element', index)" />
                                        </flexbox>
                                    </a-col>
                                </a-row>
                                <a-button type="dashed" @click="addForm('element')">
                                    <PlusOutlined />
                                    <span>添加竞争要素</span>
                                </a-button>
                            </flexbox>
                        </div>
                    </div>
                </flexbox>

                <div v-if="current === 1">
                    <h-section :title="item.name" collapse v-for="item of listForm" :key="item.name">
                        <a-table rowKey="name" :columns="columns" :data-source="item.list" :pagination="false">
                            <template #name="{ record }">
                                <a-input v-model:value="record.name" disabled />
                            </template>
                            <template #homogenize="{ record }">
                                <a-slider :max="10" v-model:value="record.homogenize" />
                            </template>
                        </a-table>
                    </h-section>
                </div>

                <div v-if="current === 2" style="margin-top: 24px">
                    <h-dot-chart :option="option" />
                </div>
            </div>
            <flexbox justify="center" class="btn-group" v-if="showStep && !disabled">
                <a-button v-if="current === 0" @click="handleReset">重置</a-button>
                <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">上一步</a-button>
                <a-button v-if="current < steps.length - 1" type="primary" style="margin-left: 8px" @click="next">下一步</a-button>
                <a-button v-if="current === 1" type="primary" style="margin-left: 8px" @click="handleCreateCanvas"> 生成画布 </a-button>
            </flexbox>
        </div>
    </h-section>
</template>

<script lang="tsx">
import { deepClone } from '@/utils/util';
import { PlusOutlined, CloseOutlined, QuestionCircleOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import { HDotChart } from '@/components';
import { message } from 'ant-design-vue';
import { useMessage } from '@/hooks/common/useMessage';
import { defineComponent, reactive, toRefs, computed } from 'vue';
export default defineComponent({
    name: 'StrategyCanvas',
    components: {
        DeleteOutlined,
        EditOutlined,
        PlusOutlined,
        CloseOutlined,
        HDotChart
    },
    props: {
        detail: { type: Object, default: () => ({}) },
        disabled: { type: Boolean, default: false }
    },
    emits: ['save'],
    setup(props, { emit }) {
        const state: any = reactive({
            current: -1,
            steps: [
                {
                    title: '设置竞品对比要素'
                },
                {
                    title: '设置产品与竞品同质化程度'
                }
            ],
            listForm: [],
            elementForm: [],
            //步骤2
            columns: [
                {
                    title: '竞争要素',
                    dataIndex: 'name',
                    key: 'name',
                    width: 200,
                    slots: { customRender: 'name' }
                },
                {
                    title: (
                        <div>
                            同质化程度
                            <a-tooltip placement="top" title="产品同质化是指产品在功能，性能上相互模仿,以至逐渐趋同的现象；越趋同，同质化程度越高">
                                <QuestionCircleOutlined style="margin-left:8px" />
                            </a-tooltip>
                        </div>
                    ),
                    dataIndex: 'homogenize',
                    key: 'homogenize',
                    slots: { customRender: 'homogenize' }
                }
            ],
            // 散点图配置
            option: {
                title: {
                    text: '战略画布离散图'
                },
                typeArr: [],
                xArr: [],
                data: []
            }
        });

        const showStep = computed((): boolean => {
            return state.current < 2 && state.current > -1;
        });

        // 校验，避免重复和空白
        const checkForm = () => {
            let res = true;
            if (!state.listForm.length) {
                res = false;
                message.error('竞品列表不能为空');
            } else {
                const required = state.listForm.every((item) => item.name);
                if (required) {
                    const nameArr = state.listForm.map((item) => item.name);
                    const newNameArr = Array.from(new Set([...nameArr]));
                    if (nameArr.length !== newNameArr.length) {
                        res = false;
                        message.error('竞品列表出现重复项');
                    }
                } else {
                    res = false;
                    message.error('竞品列表有空白项');
                }
            }
            if (res) {
                if (!state.elementForm.length) {
                    res = false;
                    message.error('竞争要素不能为空');
                } else {
                    const required = state.elementForm.every((item) => item.name);
                    if (required) {
                        const nameArr = state.elementForm.map((item) => item.name);
                        const newNameArr = Array.from(new Set([...nameArr]));
                        if (nameArr.length !== newNameArr.length) {
                            res = false;
                            message.error('竞争要素出现重复项');
                        }
                    } else {
                        res = false;
                        message.error('竞争要素有空白项');
                    }
                }
            }
            return Promise.resolve(res);
        };
        const next = () => {
            if (state.current === 0) {
                //做校验
                checkForm().then((res) => {
                    if (res) {
                        state.listForm = state.listForm.map((item) => ({
                            ...item,
                            list: deepClone(item.list) // 防止产生依赖
                        }));
                        state.current++;
                    }
                });
            } else {
                state.current++;
            }
        };
        const prev = () => {
            state.current--;
        };
        // 增加form
        const addForm = (type: string) => {
            if (type === 'element') {
                const obj = {
                    name: '',
                    homogenize: 0,
                    disable: false
                };
                state[`${type}Form`].push(obj);
                state.listForm = state.listForm.map((item) => ({
                    ...item,
                    list: [...item.list, obj]
                }));
            } else {
                state[`${type}Form`].push({
                    name: '',
                    list: [...state.elementForm]
                });
            }
        };
        // 删除form
        const deleteForm = (type: string, index: number) => {
            if (type === 'element') {
                state.listForm = state.listForm.map((item) => {
                    item.list.splice(index, 1);
                    return {
                        ...item
                    };
                });
            }
            state[`${type}Form`].splice(index, 1);
        };
        // 生成图表的配置项
        const generateOption = () => {
            state.option.typeArr = state.listForm.map((item) => item.name);
            state.option.xArr = state.elementForm.map((item) => item.name);
            state.option.data = state.listForm;
        };
        // 生成画布
        const handleCreateCanvas = () => {
            generateOption();
            state.current++;
            emit('save', state.listForm);
            // 每次保存完将该模块滚动到视图中间
            const dom = document.querySelector('.strategyCanvas-wrap');
            dom?.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
        };
        const handleAdd = () => {
            next();
        };
        const handleEdit = () => {
            state.current = 0;
        };
        const handleDelete = () => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: '确认删除当前画布？',
                iconType: 'danger',
                onOk: () => {
                    state.current = -1;
                    handleReset();
                    emit('save', state.listForm);
                }
            });
        };
        const handleReset = () => {
            state.listForm = [];
            state.elementForm = [];
        };
        // 初始化竞争要素form
        const initElementForm = () => {
            const list: any = deepClone(state.listForm[0].list);
            state.elementForm = list.map((item) => ({
                ...item,
                homogenize: 0,
                disabled: true
            }));
        };
        const init = () => {
            const strategyCanvas = JSON.parse(props.detail.strategyCanvas);
            if (strategyCanvas && strategyCanvas.length) {
                state.current = 2;
                state.listForm = strategyCanvas;
                initElementForm();
                generateOption();
            }
        };
        init();

        return {
            ...toRefs(state),
            showStep,
            next,
            prev,
            addForm,
            deleteForm,
            handleCreateCanvas,
            handleAdd,
            handleEdit,
            handleDelete,
            handleReset
        };
    }
});
</script>
<style scoped lang="less">
.plan-form-wrap {
    padding: 0 20%;
    margin: 36px auto;
    .steps-content {
        min-height: 400px;
        position: relative;
        padding: 10px 0;
        border-bottom: 1px solid #e9e9e9;
        .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        &-item {
            width: 50%;
            & + .steps-content-item {
                border-left: 1px solid #e9e9e9;
            }
            &-header {
                background: rgba(245, 245, 245, 0.5);
                height: 46px;
                font-size: 16px;
                color: #172b4d;
            }
            &-body {
                padding: 24px 48px;
                .form-item {
                    margin-bottom: 8px;
                }
            }
        }
    }
    .btn-group {
        margin-top: 32px;
    }
}
::v-deep(.ant-steps-item-description) {
    max-width: 300px !important;
}
</style>